<template>
  <div class="certificate-contract-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="权证编号">
          <el-input
            v-model="filterForm.certificateNo"
            placeholder="请输入权证编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="客户姓名">
          <el-input
            v-model="filterForm.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="办理时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="权证类型">
          <el-select v-model="filterForm.certificateType" placeholder="请选择权证类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="房产证" value="property" />
            <el-option label="土地证" value="land" />
            <el-option label="不动产证" value="real_estate" />
            <el-option label="预售证" value="presale" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="办理状态">
          <el-select v-model="filterForm.status" placeholder="请选择办理状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="申请中" value="applying" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="制证中" value="producing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 权证统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon total">
              <el-icon><Stamp /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.totalCertificates }}</div>
              <div class="stats-label">权证总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon applying">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.applyingCertificates }}</div>
              <div class="stats-label">申请中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon reviewing">
              <el-icon><View /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.reviewingCertificates }}</div>
              <div class="stats-label">审核中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon producing">
              <el-icon><Printer /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.producingCertificates }}</div>
              <div class="stats-label">制证中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon completed">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.completedCertificates }}</div>
              <div class="stats-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon rate">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ (statsData.completionRate * 100).toFixed(1) }}%</div>
              <div class="stats-label">完成率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 权证表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>权证合同列表</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增权证
            </el-button>
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出列表
            </el-button>
            <el-button type="warning" size="small" @click="handleBatchProcess" :disabled="selectedRows.length === 0">
              <el-icon><Operation /></el-icon>
              批量处理
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="certificateNo" label="权证编号" width="150" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="客户电话" width="130" />
        <el-table-column prop="propertyAddress" label="房产地址" width="200" show-overflow-tooltip />
        <el-table-column prop="certificateType" label="权证类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getCertificateTypeTag(row.certificateType)">
              {{ getCertificateTypeName(row.certificateType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyDate" label="申请日期" width="120" />
        <el-table-column prop="expectedDate" label="预计完成" width="120" />
        <el-table-column prop="actualDate" label="实际完成" width="120" />
        <el-table-column prop="status" label="办理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="办理进度" width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :color="getProgressColor(row.progress)"
              :stroke-width="8"
              text-inside
            />
          </template>
        </el-table-column>
        <el-table-column prop="fee" label="办理费用(元)" width="120" align="right">
          <template #default="{ row }">
            <span class="fee-text">{{ row.fee?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="handlerName" label="经办人" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleEdit(row)"
              :disabled="row.status === 'completed' || row.status === 'cancelled'"
            >
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="timeline">办理进度</el-dropdown-item>
                  <el-dropdown-item command="documents">相关文件</el-dropdown-item>
                  <el-dropdown-item command="notify">通知客户</el-dropdown-item>
                  <el-dropdown-item command="print">打印申请表</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 权证详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="权证详情"
      width="80%"
      @close="handleDetailDialogClose"
    >
      <div v-if="currentCertificate" class="certificate-detail">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="权证编号">{{ currentCertificate.certificateNo }}</el-descriptions-item>
              <el-descriptions-item label="客户姓名">{{ currentCertificate.customerName }}</el-descriptions-item>
              <el-descriptions-item label="客户电话">{{ currentCertificate.customerPhone }}</el-descriptions-item>
              <el-descriptions-item label="房产地址">{{ currentCertificate.propertyAddress }}</el-descriptions-item>
              <el-descriptions-item label="权证类型">
                <el-tag :type="getCertificateTypeTag(currentCertificate.certificateType)">
                  {{ getCertificateTypeName(currentCertificate.certificateType) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="申请日期">{{ currentCertificate.applyDate }}</el-descriptions-item>
              <el-descriptions-item label="预计完成">{{ currentCertificate.expectedDate }}</el-descriptions-item>
              <el-descriptions-item label="实际完成">{{ currentCertificate.actualDate || '未完成' }}</el-descriptions-item>
              <el-descriptions-item label="办理状态">
                <el-tag :type="getStatusTag(currentCertificate.status)">
                  {{ getStatusName(currentCertificate.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="办理进度">
                <el-progress
                  :percentage="currentCertificate.progress"
                  :color="getProgressColor(currentCertificate.progress)"
                />
              </el-descriptions-item>
              <el-descriptions-item label="办理费用">{{ currentCertificate.fee?.toFixed(2) || '0.00' }}元</el-descriptions-item>
              <el-descriptions-item label="经办人">{{ currentCertificate.handlerName }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="办理进度" name="timeline">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in currentCertificate.timeline"
                :key="index"
                :timestamp="item.timestamp"
                :type="item.type"
              >
                <h4>{{ item.title }}</h4>
                <p>{{ item.content }}</p>
              </el-timeline-item>
            </el-timeline>
          </el-tab-pane>
          
          <el-tab-pane label="相关文件" name="documents">
            <el-upload
              :file-list="currentCertificate.documents"
              :show-file-list="true"
              :auto-upload="false"
              list-type="text"
            >
            </el-upload>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrint">打印申请表</el-button>
        <el-button type="success" @click="handleNotifyCustomer">通知客户</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  Operation, 
  Stamp, 
  Clock, 
  View, 
  Printer, 
  CircleCheck, 
  TrendCharts,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const activeTab = ref('basic')

// 筛选表单
const filterForm = reactive({
  certificateNo: '',
  customerName: '',
  dateRange: [],
  certificateType: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计数据
const statsData = reactive({
  totalCertificates: 0,
  applyingCertificates: 0,
  reviewingCertificates: 0,
  producingCertificates: 0,
  completedCertificates: 0,
  completionRate: 0
})

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const currentCertificate = ref(null)

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
}

const handleReset = () => {
  Object.assign(filterForm, {
    certificateNo: '',
    customerName: '',
    dateRange: [],
    certificateType: '',
    status: ''
  })
  handleFilter()
}

const handleAdd = () => {
  ElMessage.info('新增权证功能开发中')
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleBatchProcess = () => {
  ElMessage.info('批量处理功能开发中')
}

const handleView = (row: any) => {
  currentCertificate.value = row
  activeTab.value = 'basic'
  detailDialogVisible.value = true
}

const handleEdit = (row: any) => {
  ElMessage.info(`编辑权证 ${row.certificateNo}`)
}

const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'timeline':
      currentCertificate.value = row
      activeTab.value = 'timeline'
      detailDialogVisible.value = true
      break
    case 'documents':
      currentCertificate.value = row
      activeTab.value = 'documents'
      detailDialogVisible.value = true
      break
    case 'notify':
      ElMessage.info(`通知客户 ${row.customerName}`)
      break
    case 'print':
      ElMessage.info(`打印申请表 ${row.certificateNo}`)
      break
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const handleDetailDialogClose = () => {
  currentCertificate.value = null
  activeTab.value = 'basic'
}

const handlePrint = () => {
  ElMessage.info('打印功能开发中')
}

const handleNotifyCustomer = () => {
  ElMessage.info('通知客户功能开发中')
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          certificateNo: 'QZ202401001',
          customerName: '张三',
          customerPhone: '13800138001',
          propertyAddress: '朝阳区某小区3号楼2单元301室',
          certificateType: 'real_estate',
          applyDate: '2024-01-15',
          expectedDate: '2024-02-15',
          actualDate: '',
          status: 'producing',
          progress: 75,
          fee: 500.00,
          handlerName: '李四',
          timeline: [
            {
              timestamp: '2024-01-15 09:00',
              title: '提交申请',
              content: '客户提交不动产证申请材料',
              type: 'primary'
            },
            {
              timestamp: '2024-01-18 14:30',
              title: '材料审核通过',
              content: '申请材料审核通过，进入制证环节',
              type: 'success'
            },
            {
              timestamp: '2024-01-25 10:00',
              title: '制证中',
              content: '不动产证正在制作中',
              type: 'info'
            }
          ],
          documents: [
            { name: '申请表.pdf', url: '/files/apply1.pdf' },
            { name: '身份证复印件.jpg', url: '/files/id1.jpg' },
            { name: '购房合同.pdf', url: '/files/contract1.pdf' }
          ]
        },
        {
          certificateNo: 'QZ202401002',
          customerName: '王五',
          customerPhone: '13800138002',
          propertyAddress: '海淀区某公寓5号楼1单元201室',
          certificateType: 'property',
          applyDate: '2024-01-14',
          expectedDate: '2024-02-14',
          actualDate: '2024-01-28',
          status: 'completed',
          progress: 100,
          fee: 300.00,
          handlerName: '赵六',
          timeline: [
            {
              timestamp: '2024-01-14 10:00',
              title: '提交申请',
              content: '客户提交房产证申请材料',
              type: 'primary'
            },
            {
              timestamp: '2024-01-20 15:00',
              title: '审核通过',
              content: '申请材料审核通过',
              type: 'success'
            },
            {
              timestamp: '2024-01-28 11:00',
              title: '证书领取',
              content: '房产证制作完成，客户已领取',
              type: 'success'
            }
          ],
          documents: []
        }
      ]
      pagination.total = 85
      
      // 更新统计数据
      Object.assign(statsData, {
        totalCertificates: 85,
        applyingCertificates: 12,
        reviewingCertificates: 18,
        producingCertificates: 25,
        completedCertificates: 30,
        completionRate: 0.82
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

// 工具方法
const getCertificateTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    property: 'primary',
    land: 'success',
    real_estate: 'warning',
    presale: 'info'
  }
  return tagMap[type] || 'info'
}

const getCertificateTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    property: '房产证',
    land: '土地证',
    real_estate: '不动产证',
    presale: '预售证'
  }
  return nameMap[type] || type
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    applying: 'info',
    reviewing: 'warning',
    producing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    applying: '申请中',
    reviewing: '审核中',
    producing: '制证中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return nameMap[status] || status
}

const getProgressColor = (progress: number) => {
  if (progress >= 80) return '#67c23a'
  if (progress >= 60) return '#e6a23c'
  if (progress >= 40) return '#f56c6c'
  return '#909399'
}

// 初始化数据
const initData = () => {
  getTableData()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.certificate-contract-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .stats-row {
    margin-bottom: 20px;
    
    .stats-card {
      .stats-item {
        display: flex;
        align-items: center;
        
        .stats-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 20px;
          color: white;
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.applying {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.reviewing {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.producing {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
          
          &.completed {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          }
          
          &.rate {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
          }
        }
        
        .stats-content {
          .stats-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 3px;
          }
          
          .stats-label {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .fee-text {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .certificate-detail {
    .el-tabs {
      margin-top: 20px;
    }
  }
}
</style>
